package serv
/*
 * Copyright (C) 2013 rdrrlabs gmail com,
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import (
    "appengine"
    "bytes"
    "html/template"
    "net/http"
)

//------------------------------

type StatusHandler struct {
    *HandlerDesc
}

func RegisterStatusHandlers(handlers Handlers) Handlers {
    // Status for non-logged users
    desc := &HandlerDesc { Title: "Status",
                           URL:   "/",
                           Flags: HandlerIsTab }
    handlers = append(handlers, &StatusHandler { desc })

    // Status for signed-in users with "view" group access
    desc  = &HandlerDesc { Title: "Status",
                           URL:   "/",
                           Flags: HandlerIsTab | HandlerIsSigned,
                           Groups: []string { GroupView } }
    handlers = append(handlers, &StatusHandler { desc })
    return handlers
}

func (p *StatusHandler) Handler() *HandlerDesc {
    return p.HandlerDesc
}

//------------------------------

const tmplTabStatus = `
<div class="row-fluid">
  <div class="span4">Select the "GCM" tab to get started.</div>
</div>
`
var mTmplTabStatus *template.Template

func (p *StatusHandler) CreateTab(r *http.Request,
                                  c appengine.Context,
                                  a *AccessInfo) template.HTML {

    if !p.Is(HandlerIsSigned) || !a.Is(GroupView) {
        // Return the status for non-logged users. Basically there's nothing for them to see.
        return template.HTML(`<em>These are not the droids you are looking for.</em>`)
    }

    if mTmplTabStatus == nil {
        mTmplTabStatus = template.Must(template.New("Status_tmpl").Parse(tmplTabStatus))
    }

    var buf bytes.Buffer
    err := mTmplTabStatus.Execute(&buf, struct { Title string } { p.Handler().Title } )
    if err == nil {
        return template.HTML(buf.String())
    }
    return template.HTML("internal error")
}

func (p *StatusHandler) ProcessRequest(w http.ResponseWriter,
                                       r *http.Request,
                                       c appengine.Context,
                                       s *AccessInfo,
                                       urlBase string,
                                       urlRest string) (httpCode int, err error) {
    return http.StatusInternalServerError, nil
}
